package cn.lisens.common.exception;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import cn.lisens.modules.cms.model.Customer;

@ControllerAdvice
public class ExceptionHandlerAdvice {
	
	@ExceptionHandler(MethodArgumentNotValidException.class)
    public String handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        
        List<ObjectError> errors = result.getAllErrors();
        for(ObjectError error : errors) {
            sb.append(" ");
            sb.append(error.getDefaultMessage());
        }

        return sb.toString();
    }
	
//	@ExceptionHandler(BindException.class)
//    public String handleBindException(BindException e) {
//        BindingResult result = e.getBindingResult();
//        StringBuilder sb = new StringBuilder();
//        
//        List<ObjectError> errors = result.getAllErrors();
//        for(ObjectError error : errors) {
//            sb.append(" ");
//            sb.append(error.getDefaultMessage());
//        }
//
//        return sb.toString();
//    }

//	@ExceptionHandler(BindException.class)
//	public String handleConstraintViolation(BindException ex,Model model) {
////		System.err.println(request.getRequestURL());
////		return new ResponseEntity<>("Validation error", HttpStatus.BAD_REQUEST);
//		model.addAttribute("msg", "error啊");
//		model.addAttribute("customer", new Customer());
//		return "modules/cms/customer-form";
//	}
	
	@ModelAttribute("msg")
	public String msg() {
		return "";
	}
}